﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Extensions.ServiceExtensions
{
    public static class StartupSwagger
    {
        /// <summary>
        /// 配置Swagger
        /// </summary>
        /// <param name="services"></param>
        /// <param name="xmlFileName">Swagger文件名称, 默认会选取入口项目文件名.xml</param>
        public static void AddSwagger(this IServiceCollection services,string xmlFileName="")
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var basePath = AppContext.BaseDirectory;
            services.AddSwaggerGen(action =>
            {
                typeof(CustomApiVersion).GetEnumNames().ToList().ForEach(version =>
                {
                    action.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title  = $"接口文档 {version}"
                    });
                    action.OrderActionsBy(o => o.RelativePath);
                });
                xmlFileName = string.IsNullOrWhiteSpace(xmlFileName) ? $"{Assembly.GetEntryAssembly().GetName().Name}.xml" : xmlFileName;
                var xmlPath = Path.Combine(basePath, xmlFileName);

                action.IncludeXmlComments(xmlPath, true);
                action.AddSecurityDefinition("Bearer",
                    new OpenApiSecurityScheme
                    {
                        In = ParameterLocation.Header,
                        Description = "请输入OAuth接口返回的Token。前置Bearer, 示例 Bearer MIX",
                        Name = "Authorization",
                        Type = SecuritySchemeType.ApiKey
                    });

                action.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference()
                            {
                                Id = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        }, Array.Empty<string>()
                    }
                });
            });
        }
    }

    public enum CustomApiVersion
    {
        V1 = 1,

        V2 = 2
    }
}
